package org.jeecg.chase.common.base.data;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import org.apache.commons.lang.StringUtils;

import java.io.StringReader;

/**
 * @author leikai
 * @version 1.0
 * @description:
 * @date 2021/08/04/0004 18:23
 */
public abstract class DataAuthorityQuery extends BaseJavaQuery {


    /**
     * 组织机构过滤
     */
    private String departId;

    /**
     * 数据权限sql
     */
    private String strategySql;

    private String id;


    @Override
    public String getSql() {
        String sql = getQuerySql();
        if (StringUtils.isNotBlank(strategySql)) {
            try {
                CCJSqlParserManager parserManager = new CCJSqlParserManager();
                Select select = (Select) parserManager.parse(new StringReader(sql));
                PlainSelect plain = (PlainSelect) select.getSelectBody();
                Expression whereStr = plain.getWhere();
                if (whereStr != null) {
                    Expression expression = new net.sf.jsqlparser.schema.Column(whereStr.toString() + " " + strategySql);
                    plain.setWhere(expression);
                } else {
                    Expression expression = new net.sf.jsqlparser.schema.Column(" 1=1 " + strategySql);
                    plain.setWhere(expression);
                }
                sql = plain.toString();
                return sql;
            } catch (JSQLParserException e) {
                e.printStackTrace();
                return null;
            }
        }
        return sql;
    }

    public String getStrategySql() {
        return strategySql;
    }

    public void setStrategySql(String strategySql) {
        this.strategySql = strategySql;
    }

    public String getDepartId() {
        return departId;
    }

    public void setDepartId(String departId) {
        this.departId = departId;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}
